package xdu.lz.stage5_jucUtils.chapter5_lock.readwritelock;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created at 2019/10/19 0019 下午 9:18
 *
 * 读可以并行，写串行
 *
 * 这样实现不了
 */
public class ReadWriteLock2 {

    private final static ReadWriteLock lock = new ReentrantReadWriteLock(true);

    private final static Lock readLock = lock.readLock();

    private final static Lock writeLock = lock.writeLock();

    private final static List<Long> data = new ArrayList<>();

    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(10);

        for (int i = 0; i < 9; i++) {
            service.submit(ReadWriteLock2::read);
        }
        service.submit(ReadWriteLock2::write);
    }

    public static void write(){
        while (true){
            try {
                writeLock.lock();
                Thread.sleep(100);
                data.add(System.currentTimeMillis());
                System.out.println("write lock");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                writeLock.unlock();
            }
        }

    }


    public static void read(){
        while (true){
            try {
                readLock.lock();
                Thread.sleep(100);
//                data.forEach(System.out::println);
                System.out.println("read lock");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                readLock.unlock();
            }
        }

    }
}
